from __future__ import annotations

import json
from pathlib import Path
from typing import Dict, Any, TextIO

class Serializer:
    def __init__(self, stream: TextIO):
        self.stream = stream

    def emit(self, payload: Dict[str, Any]) -> None:
        raise NotImplementedError

class NDJSONSerializer(Serializer):
    def emit(self, payload: Dict[str, Any]) -> None:
        json.dump(payload, self.stream, ensure_ascii=False)
        self.stream.write("\n")
        self.stream.flush()

def build_serializer(config: Dict[str, Any]) -> Serializer:
    logging_cfg = config.get("logging", {})
    fmt = logging_cfg.get("format", "ndjson")
    target = logging_cfg.get("file", "snapshots.ndjson")

    Path(target).parent.mkdir(parents=True, exist_ok=True)
    file_handle = open(target, "w", encoding="utf-8")

    if fmt == "ndjson":
        return NDJSONSerializer(file_handle)
    else:
        raise ValueError(f"Unsupported logging format: {fmt}")